<template>
  <div class="container-content">
    <div class="drag-container">
      <el-row>
        <el-text tag="b">选择表单</el-text>
      </el-row>
      <el-row>
        <el-select v-model="formData.formId" @change="formChange">
          <el-option v-for="item in formSelectList" :key="item.formId" :label="item.formName" :value="item.formId" />
        </el-select>
      </el-row>
      <el-row class="flex justify-between">
        <el-text tag="b">待选列名</el-text>
        <el-checkbox v-model="formData.fieldCheckAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange"
          :border="false" v-if="formData.formId">
          全选
        </el-checkbox>
      </el-row>
      <div class="field-box">
        <template v-if="formData.formId">
          <el-checkbox-group v-model="formData.fieldGroup" @change="handleCheckeBoxChange">
            <el-checkbox class="custom-checkbox" v-for="item in formData.fieldCheckBox" :label="item.fieldText"
              :value="item.fieldName" :border="false" />
          </el-checkbox-group>
        </template>
        <template v-else>
          <el-empty description="选择表单展示可选字段" />
        </template>
      </div>
      <el-row>
        <el-text tag="b">已选列名</el-text>
      </el-row>
      <template v-if="formData.fieldGroup.length > 0">
        <VueDraggable v-model="checkedColumn" target=".drag-header" class="drag-table">
          <el-table :data="tableList" :border="true" :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
            :header-row-class-name="'drag-header'" :header-cell-class-name="'drag-header-cell'">
            <el-table-column v-for="item in checkedColumn" :prop="item.fieldName" :label="item.fieldText"
              :sortable="item.isSort">
              <template #header>
                {{ item.fieldText }}
                <el-icon :size="14" class="drag-header-delete" @click="deleteColumn(item.fieldName)">
                  <CloseBold />
                </el-icon>
              </template>
              <template #default="scope">
                <el-button :type="isSelectColumn && isSelectColumn.fieldName === item.fieldName ? 'primary' : 'default'"
                  @click="clickColumn(item)">设置</el-button>
              </template>
            </el-table-column>
          </el-table>
        </VueDraggable>
      </template>
      <template v-else>
        <el-empty description="选择字段展示表格" />
      </template>
    </div>
    <ListControlSetting v-model="formData" :isSelectColumn="isSelectColumn" />
  </div>
</template>

<script setup lang="ts">
import { VueDraggable } from "vue-draggable-plus";
import DesignFormApi, { DesignFormSelect } from '@/api/design/designForm';
import { CheckboxValueType } from 'element-plus';
import { DesignListTableConfig, ListSetting } from '.';

const formData = defineModel<ListSetting>();

const checkedColumn = defineModel<DesignListTableConfig[]>("checkedColumn");

const formSelectList = ref<DesignFormSelect[]>([]);

onMounted(async () => {
  const list = await DesignFormApi.select();
  formSelectList.value = list;
})

const tableList = computed(() => {
  const data = {};
  formData.value.tableConfig.map(x => {
    data[x.fieldName] = "示例数据";
  });
  return [data];
})

const formChange = async (formId: string) => {
  const list = await DesignFormApi.queryFieldSelect(formId);
  formData.value.fieldCheckBox = list;
  formData.value.fieldGroup = [];
  formData.value.fieldCheckAll = false;
}

const isIndeterminate = computed(() => {
  return formData.value.fieldGroup.length > 0 && formData.value.fieldGroup.length < formData.value.fieldCheckBox.length;
});
const handleCheckAllChange = (val: CheckboxValueType) => {
  formData.value.fieldGroup = val ? formData.value.fieldCheckBox.map(x => x.fieldName) : [];
}
const handleCheckeBoxChange = (value: CheckboxValueType[]) => {
  const checkedCount = value.length;
  formData.value.fieldCheckAll = checkedCount === formData.value.fieldCheckBox.length;
}

// 监听多选框,更新拖拽数组
watch(() => formData.value.fieldGroup, (newVal) => {
  // 根据选中的列名过滤出对应的列配置
  const newColumns = formData.value.fieldCheckBox
    .filter(col => newVal.includes(col.fieldName))
    // 保持原有排序，如果是新添加的列则放在最后
    .sort((a, b) => {
      const indexA = checkedColumn.value.findIndex(item => item.fieldName === a.fieldName);
      const indexB = checkedColumn.value.findIndex(item => item.fieldName === b.fieldName);

      // 如果两列都在原有排序中，则保持原有顺序
      if (indexA !== -1 && indexB !== -1) {
        return indexA - indexB;
      }
      // 如果只有一列在原有排序中，则它排在前面
      if (indexA !== -1) return -1;
      if (indexB !== -1) return 1;
      // 两列都不在原有排序中，按默认顺序
      return newVal.indexOf(a.fieldName) - newVal.indexOf(b.fieldName);
    });

  //如果是修改页面，需要从已有数据取，用于回显数据
  // 构建 tableConfig 中字段的映射表，便于快速查找
  const tableConfigMap = new Map(formData.value.tableConfig.map(col => [col.fieldName, col]));

  // 遍历 newColumns，优先取 tableConfig 中存在的字段，否则用 newColumns 自身的
  checkedColumn.value = newColumns.map(newCol => {
    const existingCol = tableConfigMap.get(newCol.fieldName);
    return existingCol ? existingCol : newCol;
  });
})

const deleteColumn = (value: string) => {
  formData.value.fieldGroup = formData.value.fieldGroup.filter(x => x != value);
}

// 选中列设置
const isSelectColumn = ref<DesignListTableConfig>();
const clickColumn = (column: DesignListTableConfig) => {
  isSelectColumn.value = column;
}
</script>

<style lang="scss" scoped>
.drag-container {
  flex: 1;
  padding: 10px;
  border-right: 1px solid var(--el-border-color);
  overflow-x: auto;
}

.custom-checkbox {
  margin-bottom: 10px;
}

:deep(.drag-header-cell) {
  font-size: 14px;
}

.drag-header-cell:hover .drag-header-delete {
  display: inline-block;
  cursor: pointer;
}

.drag-header-delete {
  display: none;
}
</style>
